package netTrackerGUI;


/**
 * A class to handle attempts at cell selection. It
 * will check to see if any other user has the cell
 * selected, and will not select the cell if they do.
 * It sets a flag based on the success of the operation.
 * 
 * @author David Cummings
 * 
 */
public class CellOutliner{
	TrackerPanel trackerPanel;
	CellGUI cell;
	/** The direction of movement */
	int moveX;
	int moveY;
	/** Indicates whether the outliner is trying to move in a certain direction. */
	boolean moving;
	int outlineID;
	boolean success;
	
	/**
	 * Constructs a cell outliner to move a cell outline, given a direction to move.
	 * @param trackerPanel The tracker panel creating the thread.
	 * @param outlinedCell The cell to move the outline from.
	 * @param moveX the x amount to move. (positive is right)
	 * @param moveY the y amount to move. (positive is down)
	 * @param outlineID the ID of the node outlining the cell.
	 */
	public CellOutliner(TrackerPanel trackerPanel, int moveX, int moveY, int outlineID){
		this.trackerPanel = trackerPanel;
		this.moveX = moveX;
		this.moveY = moveY;
		CellGUI outlinedCell = trackerPanel.getOutlinedCell(outlineID);
		this.cell = trackerPanel.getCell(outlinedCell.getCellX()+moveX,outlinedCell.getCellY()+moveY);
		this.outlineID = outlineID;
		moving = true;
		success = false;
	}
	/**
	 * Constructs a cell outliner to try to move to a given cell outline without a direction.
	 * @param trackerPanel The tracker panel creating the thread.
	 * @param targetCell The cell to move to.
	 * @param outlineID the ID of the node outlining the cell.
	 */
	public CellOutliner(TrackerPanel trackerPanel, CellGUI targetCell, int outlineID){
		this.trackerPanel = trackerPanel;
		this.cell = targetCell;
		this.outlineID = outlineID;
		moveX = 0;
		moveY = 0;
		moving = false;
		success = false;
	}
	
	/**
	 * Attempts to outline a cell. Synchronized to 
	 * prevent the state of a cell changing during checks.
	 */
	public synchronized void attemptOutlineCell() {
		if(trackerPanel.isLocking()){
			if(cell.getCell().isSelected() || cell.getCell().isOutlined()){
				if (moving){	// If moving, keep trying to move until reaching an unselected cell.
					do{
						cell = trackerPanel.getCell(cell.getCellX()+moveX,cell.getCellY()+moveY);
					}while(cell.getCell().isSelected());
					// At this point, we have reached a cell that is not outlined.
					outlineCell();
				}
			}else{
				outlineCell();
			} // end if (cell is selected)
		} else {
			outlineCell();
		} // end if (locking)
	}
	private void outlineCell(){
		success = true;
		CellGUI current = trackerPanel.getOutlinedCell(outlineID);
		if(current!=null)
			current.unoutline(outlineID);
		cell.outline(outlineID);
		trackerPanel.setOutlinedCell(cell, outlineID);
	}
	
	public boolean wasSuccessful(){
		return success;
	}
}